<script setup>
import TopBarTwo from '@/components/TopBarTwo.vue'
import SortBar from '@/components/SortBar.vue'
import { goBack, judgeShowImage, uniNavigateTo } from '@/utils'
import OrderApi from '@/service/order'
import { useDictStore } from '@/store/dict'
import { getDictDetail, dictMap, getProgrammeCategory } from '@/service/dict'
import { useUserStore } from '@/store/user'
import { useMessage } from 'wot-design-uni'
import BasePopup from '@/components/BasePopup.vue'

// 获取状态栏高度
const { statusBarHeight } = uni.getSystemInfoSync()

const dictStore = useDictStore()

const userStore = useUserStore()

const message = useMessage()

onLoad(() => {
  // 监听预约成功事件
  uni.$on('bookingOrderSuccess', () => {
    refreshList()
  })
})

onUnload(() => {
  // 移除预约成功事件
  uni.$off('bookingOrderSuccess')
})

const tabList = ref([])
const activeTab = ref('')

const getDict = async () => {
  const { code, result } = await getDictDetail(dictMap.orderType)
  return code === 200 && result ? result : []
}
const initDict = async () => {
  // const { orderType } = dictStore.dictData
  // let dictItem = orderType
  // if (!orderType) {
  //   dictItem = await getDict()
  // }
  const dictItem = await getDict()
  tabList.value = [{ label: '全部', value: '' }, ...dictItem]
}

// const tabList = computed(() => {
//   const { orderType } = dictStore.dictData
//   return [{ label: '全部', value: '' }, ...orderType]
// })

const handleCheckTab = (val) => {
  activeTab.value = val
  refreshList()
}

const sortList = [
  { label: '点单最多', value: 'realTimes', type: 0 },
  { label: '最新发布', value: 'createTime', type: 2 }, // 默认按时间倒叙
]
const sortObj = ref({
  order: 'desc',
  column: 'createTime',
}) // 默认按时间倒叙

const handleCheckSort = (val) => {
  console.log('val', val)
  const { sortType, value } = val
  sortObj.value = {
    order: sortType,
    column: value,
  }
  refreshList()
}

/** ----------- 筛选项 start ---------- */
const categoryState = reactive({
  visible: false,
  currentValue: '',
  currentLabel: '',
  columns: [],
})
const getCategoryList = async () => {
  const { code, result } = await getProgrammeCategory()
  if (code === 200 && result) {
    categoryState.columns = result
    categoryState.currentValue = ''
    categoryState.currentLabel = '全部类型'
  }
}
const checkCategory = (child) => {
  if (child) {
    categoryState.currentValue = child.value
    categoryState.currentLabel = child.label
  } else {
    categoryState.currentValue = ''
    categoryState.currentLabel = '全部类型'
  }
  refreshList()
  categoryState.visible = false
}
/** ----------- 筛选项 end ---------- */

/** ----------- 分页加载 start --------- */
const pageObj = ref({
  pageNo: 1,
  pageSize: 10,
})
const scrollState = reactive({
  refresherTriggered: false,
  dataList: [],
  loadState: 'loading',
})

const getDataList = async () => {
  if (scrollState.loadState === 'finished') return
  try {
    const params = {
      ...pageObj.value,
      // type: activeTab.value,
      type: categoryState.currentValue || '',
      ...sortObj.value,
    }
    const { code, result } = await OrderApi.getShareOrderPage(params)
    if (code === 200 && result) {
      const { records, pages } = result
      if (records?.length) {
        scrollState.dataList = [...scrollState.dataList, ...records]
      }
      if (pageObj.value.pageNo < pages) {
        pageObj.value.pageNo++
      } else {
        scrollState.loadState = 'finished'
      }
    } else {
      scrollState.loadState = 'error'
    }
  } catch (e) {
    scrollState.loadState = 'error'
  }
}

const reset = () => {
  pageObj.value.pageNo = 1
  scrollState.dataList = []
  scrollState.loadState = 'loading'
}

const onRefresherrefresh = async () => {
  scrollState.refresherTriggered = true
  await refreshList()
  scrollState.refresherTriggered = false
}

const refreshList = async () => {
  try {
    uni.showLoading()
    reset()
    await getDataList()
  } finally {
    uni.hideLoading()
  }
}
/** ----------- 分页加载 end --------- */

const goPage = (path) => {
  console.log('path', path)
  if (userStore.isLogined) {
    uniNavigateTo(path)
  } else {
    message
      .confirm({
        msg: '您还未登录，是否去登录？',
        title: '提示',
      })
      .then(() => {
        uniNavigateTo('/pages/login/index')
      })
      .catch(() => {
        console.log('点击了取消按钮')
      })
  }
}

onMounted(async () => {
  // await initDict()
  await getCategoryList()
  refreshList()
  // handleCheckTab(tabList.value[0].value)
})
</script>

<template>
  <view
    class="flex flex-col"
    :style="{
      height: `calc(100vh - ${statusBarHeight}px - 204rpx)`,
    }"
  >
    <view>
      <!-- <TopBarTwo
        :tab-list="tabList"
        :active-tab="activeTab"
        @check="handleCheckTab"
      /> -->
      <view class="p-24rpx flex">
        <view class="filter-bar flex-1 mr-24rpx">
          <view
            class="filter-bar-item"
            @click="categoryState.visible = true"
          >
            <view class="filter-bar-item-text ellipsis">
              {{ categoryState.currentLabel }}
            </view>
            <view class="filter-bar-item-icon">
              <image
                class="h-32rpx w-32rpx"
                src="/static/icons/filter-arrow.png"
              />
            </view>
          </view>
        </view>
        <view class="flex-[2]">
          <SortBar
            :sort-list="sortList"
            @check="handleCheckSort"
          />
        </view>
      </view>
    </view>
    <scroll-view
      class="scroll-container"
      scroll-y
      refresher-enabled
      enable-back-to-top
      :refresher-triggered="scrollState.refresherTriggered"
      @refresherrefresh="onRefresherrefresh"
      @scrolltolower="getDataList"
    >
      <template v-if="scrollState.dataList.length">
        <view class="flex flex-wrap">
          <view
            v-for="item in scrollState.dataList"
            :key="item.id"
            class="scroll-item-wrap"
          >
            <view
              class="scroll-item"
              @click="
                uniNavigateTo(
                  `/pages-sub/share-menu/detail/index?id=${item.id}`,
                )
              "
            >
              <image
                class="scroll-item-img"
                :src="judgeShowImage(item.coverUrl)"
              ></image>
              <view class="scroll-item-title ellipsis">{{ item.name }}</view>
              <view class="scroll-item-desc ellipsis">
                供单单位：{{ item.sysOrgCode_dictText }}
              </view>
              <view class="scroll-item-desc">
                剩余场次：{{ item.realResourceTimes }}
              </view>
            </view>
          </view>
        </view>
        <wd-loadmore
          finished-text="没有更多了"
          :state="scrollState.loadState"
          @reload="getDataList"
        />
      </template>
      <wd-status-tip
        v-else
        image="content"
        tip="暂无内容"
      />
    </scroll-view>
    <!-- <view class="float-btn" @click="goPage('/pages-sub/activity/add/index')">
      <image class="w-full h-full" src="@/static/icons/float-btn-share.png"></image>
    </view> -->

    <wd-message-box />

    <!-- 类型弹窗 -->
    <BasePopup
      v-model:visible="categoryState.visible"
      title="请选择"
    >
      <view class="category-group">
        <view class="category-item">
          <view class="flex flex-wrap">
            <view
              class="category-item-child"
              :class="{ active: categoryState.currentValue === '' }"
              @click="checkCategory()"
            >
              全部类型
            </view>
          </view>
        </view>
        <view
          v-for="item in categoryState.columns"
          :key="item.value"
          class="category-item"
        >
          <view class="category-item-title">{{ item.label }}</view>
          <view
            v-if="item.children?.length"
            class="flex flex-wrap"
          >
            <view
              v-for="child in item.children"
              :key="child.value"
              class="category-item-child"
              :class="{ active: categoryState.currentValue === child.value }"
              @click="checkCategory(child)"
            >
              {{ child.label }}
            </view>
          </view>
        </view>
      </view>
    </BasePopup>
  </view>
</template>

<style lang="scss" scoped>
.scroll-container {
  padding: 0 12rpx;
  box-sizing: border-box;
}

.scroll-item {
  padding: 24rpx 16rpx;
  background: #fff;
  border-radius: 16rpx;

  &-wrap {
    width: 50%;
    padding: 12rpx;
    box-sizing: border-box;
  }

  &-img {
    width: 100%;
    height: 208rpx;
    margin-bottom: 24rpx;
    border-radius: 16rpx;
  }

  &-title {
    margin-bottom: 16rpx;
    font-size: 28rpx;
    color: $uni-text-color;
    font-weight: 500;
  }

  &-desc {
    margin-bottom: 16rpx;
    font-size: 24rpx;
    color: $uni-text-color-grey;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.float-btn {
  position: fixed;
  bottom: 100rpx;
  right: 24rpx;
  z-index: 1;
  width: 128rpx;
  height: 128rpx;
}

.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-radius: 16rpx;

  &-item {
    position: relative;
    display: flex;
    flex: 1;
    align-items: center;
    justify-content: center;
    height: 80rpx;

    &::after {
      position: absolute;
      top: 50%;
      right: 0;
      width: 1rpx;
      height: 32rpx;
      content: '';
      background-color: $uni-border-color;
      transform: translateY(-50%);
    }

    &:last-child {
      &::after {
        display: none;
      }
    }

    &-text {
      max-width: 170rpx;
      font-size: 28rpx;
      color: $uni-text-color;

      &.active {
        color: #f98f18;
      }
    }
  }
}

.category-group {
  padding: 32rpx;
  max-height: 50vh;
  overflow-y: auto;

  .category-item {
    margin-bottom: 16rpx;

    &-title {
      position: relative;
      padding-left: 24rpx;
      margin-bottom: 16rpx;
      font-size: 30rpx;
      font-weight: 500;
      color: $uni-text-color;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8rpx;
        height: 32rpx;
        background-image: linear-gradient(169deg, #67bdf6 0%, #2c84db 100%);
        border-radius: 2rpx;
      }
    }

    &-child {
      min-width: 180rpx;
      padding: 12rpx;
      margin: 0 16rpx 16rpx 0;
      font-size: 26rpx;
      color: $uni-text-color-grey;
      text-align: center;
      background: #f4f7fc;
      box-sizing: border-box;
      border-radius: 8rpx;

      &.active {
        background: rgba(249, 143, 24, 0.2);
        color: #f98f18;
      }
    }
  }
}
</style>
